using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

namespace Gj
{
    public class AndroidDownload
    {
        static AndroidJavaObject activity =
            new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");

        private static UnityWebRequest request;

        public static float Process()
        {
            if (request == null)
            {
                return 0;
            }

            return request.downloadProgress;
        }
        
        public static IEnumerator Download(string url, Action<string> callback)
        {
            if (request != null)
            {
                callback(null);
                yield break;
            }
            Debug.Log("download: "+url);
            AnalyticsManager.Event("downloadAndroidStart", new Dictionary<string, object>{{"url", url}});
            request = UnityWebRequest.Get(url);
            yield return request.SendWebRequest();
            if (request.isDone)
            {
                Debug.Log("download success: "+url);
                AnalyticsManager.Event("downloadAndroidSuccess", new Dictionary<string, object>{{"url", url}});
                string path = Application.persistentDataPath + "/"+Path.GetFileName(url);
                File.WriteAllBytes(path, request.downloadHandler.data);
                path = path.Replace(":", "");
                callback(path);
            }
            else
            {
                Debug.Log("download fail: "+url);
                AnalyticsManager.Event("downloadAndroidFail", new Dictionary<string, object>{{"url", url}});
                callback(null);
            }

            request = null;
        }
        
        public static void Install(string path)
        {
            AndroidJavaObject pluginObject = new AndroidJavaClass("com.ueffort.apk.InstallApk").CallStatic<AndroidJavaObject>("GetInstance");
            pluginObject.Call("installApp", path);
        }
    }
}